package com.woniuxy.listenner;

import com.woniuxy.utils.RedisUtil;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class EmailListener {
    @Autowired
    private RedisUtil redisUtil;

    @RabbitListener(queues = "email-queue")
    public void processEmailMessage(String email) throws MessagingException {
        System.out.println("监听到的email: " + email);
        String code = generateAlphanumericCode();
        String key =  email;
        // 验证码存入redis，用于校验
        redisUtil.set(key, code, 5, TimeUnit.MINUTES);
        // 发件人邮箱地址和授权码
        String senderEmail = "13674452978@163.com";
        String senderPassword = "CMi9DKMbaeAFrFF9"; // 注意这里不是邮箱密码，而是授权码

        // 收件人邮箱地址
        String recipientEmail = email;

        // 邮件主题和内容
        String subject = "智慧社区";
        String content = "【智慧社区平台】您的登录验证码是：" +code + "，5 分钟内有效。请勿向他人泄露，如非本人操作请忽略";


        sendEmail(senderEmail, senderPassword, recipientEmail, subject, content);
        System.out.println("邮件发送成功！");


    }
    // 发送邮件
    public static void sendEmail(String senderEmail, String senderPassword, String recipientEmail,
                                 String subject, String content) throws MessagingException {
        // 配置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.163.com"); // 163邮箱的SMTP服务器地址
        properties.put("mail.smtp.port", "25"); // 163邮箱的SMTP服务器端口

        // 创建认证器
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        };

        // 创建会话
        Session session = Session.getInstance(properties, authenticator);

        // 创建邮件消息
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(senderEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject(subject);
        message.setText(content);

        // 发送邮件
        Transport.send(message);
    }

    // 生成随机字母数字验证码
    public String generateAlphanumericCode() {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder code = new StringBuilder();

        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(chars.length());
            code.append(chars.charAt(index));
        }

        return code.toString();
    }
}
